package com.bing.util;

import com.bing.beans.Person;
import com.bing.beans.WeiBo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kaibb on 14-8-3.
 */
public class ExcelUtil {

    public static final Map<Integer, String> userheaders = new HashMap<Integer, String>();
    public static final Map<Integer, String> weiBoheaders = new HashMap<Integer, String>();
    public static final Map<Integer, String> weiBoSearchheaders = new HashMap<Integer, String>();

    public static final Map<Integer, String> guanZhuheaders = new HashMap<Integer, String>();

    private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm");

    public static final String data_STR = "采集数据/";
    public static String DATA_DIR = System.getProperty("app.home") == null ? data_STR : System.getProperty("app.home") + "/" + data_STR;
    public static int Total = 0;


    private HSSFSheet sinaSheet = null;
    private HSSFSheet weiboSheet = null;
    private HSSFSheet guanZhuSheet = null;
    private HSSFSheet fenSiSheet = null;
    private HSSFWorkbook sinaBook = null;
    private File dataFile;
    private FileOutputStream os = null;

    static {
        // String _headers = "分类-fenLei|受理编号-bianHao|举报次数-browse|举报时间-weiboTime|举報人姓名-juBaoPerson.userName|";
        String user_headers = "用户名-userName|认证-renZheng|等级-dengJi|活跃天数-huoYue|关注数-guanZhu|粉丝数-fenSi|微博数-weiBoShu|积分-jiFen|采集时间-createdTime";

        String weiBo_headers = "内容-content|时间-create_date|赞-zan|转发-zhuangFa|评论-pingLun|收藏-shouCang";

        String guanZhu_headers = "用户名-userName|认证-renZheng|关注数-guanZhu|粉丝数-fenSi|微博数-weiBoShu";

        String weiBoSearch_headers = "用户名-person.userName|认证-person.renZheng|等级-person.dengJi|活跃天数-person.huoYue|关注数-person.guanZhu|粉丝数-person.fenSi|微博数-person.weiBoShu|积分-person.jiFen|微博内容-content|发布时间-create_date|赞-zan|转发-zhuangFa|评论数-pingLun|收藏-shouCang|转发粉丝数和-zhuangFaFenSiHe|评论-pingLuns";


        int i = 0;
        for (String header : StringUtils.tokenizeToStringArray(user_headers, "|")) {
            userheaders.put(i++, header);
        }
        i = 0;
        for (String header : StringUtils.tokenizeToStringArray(weiBo_headers, "|")) {
            weiBoheaders.put(i++, header);
        }
        i = 0;
        for (String header : StringUtils.tokenizeToStringArray(guanZhu_headers, "|")) {
            guanZhuheaders.put(i++, header);
        }
        i = 0;
        for (String header : StringUtils.tokenizeToStringArray(weiBoSearch_headers, "|")) {
            weiBoSearchheaders.put(i++, header);
        }


        logger.info("Excel 表头：user:{},weibo:{},guanZhu:{},内容搜索:{}", userheaders, weiBoheaders, guanZhuheaders, weiBoSearchheaders);
    }

    static {
        try {
            File dir = ResourceUtils.getFile(DATA_DIR);
            if (!dir.exists()) {
                System.out.println("文件不存在");
                dir.mkdir();
            }
        } catch (FileNotFoundException e) {
        } catch (Exception e) {
        }

    }

    public ExcelUtil(String userName, String dataStr) throws FileNotFoundException {
        init(userName, dataStr);
    }

    public ExcelUtil(String content) throws FileNotFoundException {
        init(content);
    }

    public void init(String content) throws FileNotFoundException {
        //创建Excel的工作书册 Workbook, 对应到一个excel文档
        sinaBook = new HSSFWorkbook();

        weiboSheet = sinaBook.createSheet("微博");
        // 设置excel每列宽度
        weiboSheet.setColumnWidth(1, 3500);
        createShell(sinaBook);
        HSSFRow row = weiboSheet.createRow(0);
        for (int j : weiBoSearchheaders.keySet()) {
            row.createCell(j).setCellValue(StringUtils.split(weiBoSearchheaders.get(j), "-")[0]);
        }
        dataFile = ResourceUtils.getFile(DATA_DIR + content + "-" + sdf.format(new Date()) + ".xls");
    }

    private void createShell(HSSFWorkbook sinaBook) {
        HSSFFont font = sinaBook.createFont();
        font.setFontName("Verdana");
        font.setBoldweight((short) 100);
        font.setFontHeight((short) 300);
        font.setColor(HSSFColor.BLUE.index);
        // 创建单元格样式
        HSSFCellStyle style = sinaBook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        // 设置边框
        style.setBottomBorderColor(HSSFColor.RED.index);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setFont(font);// 设置字体

    }

    public void init(String userName, String dataStr) throws FileNotFoundException {
        //创建Excel的工作书册 Workbook, 对应到一个excel文档
        sinaBook = new HSSFWorkbook();
        // 创建Excel的工作sheet,对应到一个excel文档的tab
        sinaSheet = sinaBook.createSheet("用户");
        // 设置excel每列宽度
        sinaSheet.setColumnWidth(1, 3500);

        // 创建Excel的工作sheet,对应到一个excel文档的tab
        weiboSheet = sinaBook.createSheet("微博");
        // 设置excel每列宽度
        weiboSheet.setColumnWidth(1, 3500);

        // 创建Excel的工作sheet,对应到一个excel文档的tab
        fenSiSheet = sinaBook.createSheet("粉丝");
        // 设置excel每列宽度
        fenSiSheet.setColumnWidth(1, 3500);

        // 创建Excel的工作sheet,对应到一个excel文档的tab
        guanZhuSheet = sinaBook.createSheet("关注");
        // 设置excel每列宽度
        guanZhuSheet.setColumnWidth(1, 3500);
        // 创建字体样式
        createShell(sinaBook);
        HSSFRow row = sinaSheet.createRow(0);
        for (int j : userheaders.keySet()) {
            row.createCell(j).setCellValue(StringUtils.split(userheaders.get(j), "-")[0]);
        }

        row = weiboSheet.createRow(0);
        for (int j : weiBoheaders.keySet()) {
            row.createCell(j).setCellValue(StringUtils.split(weiBoheaders.get(j), "-")[0]);
        }

        row = fenSiSheet.createRow(0);
        for (int j : guanZhuheaders.keySet()) {
            row.createCell(j).setCellValue(StringUtils.split(guanZhuheaders.get(j), "-")[0]);
        }

        row = guanZhuSheet.createRow(0);
        for (int j : guanZhuheaders.keySet()) {
            row.createCell(j).setCellValue(StringUtils.split(guanZhuheaders.get(j), "-")[0]);
        }
        dataFile = ResourceUtils.getFile(DATA_DIR + userName + "-" + dataStr + ".xls");
    }

    public void closeWrite() {
        try {
            os = new FileOutputStream(dataFile);
            sinaBook.write(os);
            os.close();
        } catch (Exception e) {

        } finally {
        }
    }

    public void writePerson(Person person) {
        putData(sinaSheet, person, userheaders);
    }

    public void writeFenSi(Person person) {
        putData(fenSiSheet, person, guanZhuheaders);
    }

    public void writeGuanZhu(Person person) {
        putData(guanZhuSheet, person, guanZhuheaders);
    }

    public void writeWeiBo(WeiBo weiBo) {
        putData(weiboSheet, weiBo, weiBoheaders);
    }

    public void writeWeiBoContent(WeiBo weiBo) {
        putData(weiboSheet, weiBo, weiBoSearchheaders);
    }

    public void writeAll(Person person) {

    }

    private void putData(HSSFSheet sheet, Object o, Map<Integer, String> headers) {
// 创建Excel的sheet的一行
        logger.info("写:{} , 数据:{}", sheet, o);
        // 创建Excel的sheet的一行
        HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
        for (int j : headers.keySet()) {
            String value = "NA";
            try {
                if (headers.get(j).equals("评论-pingLuns")) {
                    WeiBo wb = (WeiBo) o;
                    StringBuilder sb = new StringBuilder();
                    int i=0;
                    for (String pinLun : wb.getPingLuns()) {
                        i++;
                        sb.append(i+": " + pinLun + "\n");
                    }
                    value = sb.toString();
                } else {
                    value = BeanUtils.getProperty(o, StringUtils.split(headers.get(j), "-")[1]);
                }
            } catch (Exception e) {
                logger.error("", e);
            }
            row.createCell(j).setCellValue(value);
            logger.debug("设置:{},{},{}", j, headers.get(j), value);
        }
    }
}
